package com.study.common.constants;

import com.study.common.constants.RedisKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisCache {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void setRepeatSubmit(String key,String data,int time){
        stringRedisTemplate.opsForValue().set(RedisKey.repeatSubmit(key),data,time, TimeUnit.MILLISECONDS);
    }

    public String getRepeatSubmit(String key){
        return stringRedisTemplate.opsForValue().get(RedisKey.repeatSubmit(key));
    }

    public void setUserToken(String token, String uuid) {
        stringRedisTemplate.opsForValue().set(RedisKey.userToken(token), uuid, 12L, TimeUnit.HOURS);
    }

    public String getUserToken(String token) {
        return stringRedisTemplate.opsForValue().get(RedisKey.userToken(token));
    }

    public void deletedUserToken(String token) {
        stringRedisTemplate.delete(RedisKey.userToken(token));
    }

    public void setMiniToken(String token, String json) {
        stringRedisTemplate.opsForValue().set(RedisKey.miniToken(token), json, 2L, TimeUnit.HOURS);
    }

    public String getMiniToken(String token) {
        return stringRedisTemplate.opsForValue().get(RedisKey.miniToken(token));
    }

    public void setCurrentUser(String uuid, String jsonUser) {
        stringRedisTemplate.opsForValue().set(RedisKey.currentUser(uuid), jsonUser, 12L, TimeUnit.HOURS);
    }

    public String getCurrentUser(String uuid) {
        return stringRedisTemplate.opsForValue().get(RedisKey.currentUser(uuid));
    }

    public void deletedCurrentUser(String uuid) {
        stringRedisTemplate.delete(uuid);
    }

    public List<String> getMenus(List<Integer> menuIds){
        List<String> list = new ArrayList<>();
        for (Integer menuId : menuIds) {
            String s = stringRedisTemplate.opsForValue().get(RedisKey.menu(menuId));
            if(StringUtils.isNotBlank(s)){
                list.add(s);
            }
        }
        return list;
    }

    public void setMenu(Integer id,String jsonMenu){
        stringRedisTemplate.opsForValue().set(RedisKey.menu(id),jsonMenu);
    }

    public String getMenu(Integer id){
        return stringRedisTemplate.opsForValue().get(RedisKey.menu(id));
    }

    public void deletedMenu(Integer id){
        stringRedisTemplate.delete(RedisKey.menu(id));
    }

    public void setAppContext(String token,String appContext){
        stringRedisTemplate.opsForValue().set(RedisKey.miniToken(token),appContext);
    }

    public String getAppContext(String token){
        return stringRedisTemplate.opsForValue().get(RedisKey.miniToken(token));
    }
}
